asp.net MVC

Mvc-show error message along with image

Mvc-show error message along with image, someone asked me to explain?

In this article, I will show you how to display images along with Validation message using dataannotations in mvc asp.net c#.

Here, I want to check the string length for the CategoryName using the ErrorMessage property of StringLength attribute along with HTML markup tag.

Category class: custom validation in mvc for CategoryName property.

public partial class Category
    {

      public int CategoryID { get; set; }

        [Required]
        [StringLength(15, ErrorMessage = "<imgsrc='/Images/error.png' /> category name should not exceed the max lengththan 15!")]
        public string CategoryName { get; set; }
        public string Description { get; set; }

    }

Create view: asp.net mvc form validation

<fieldset>
        <legend>Category</legend>
 
        <div class="editor-label">
            @Html.LabelFor(model => model.CategoryName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.CategoryName)
            @Html.Raw(HttpUtility.HtmlDecode(
            @Html.ValidationMessageFor(model=> model.CategoryName).ToHtmlString()))
        </div>
 
        <div class="editor-label">
            @Html.LabelFor(model => model.Description)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Description)
            @Html.ValidationMessageFor(model => model.Description)
        </div>
 
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>

In the create view we should decode the plain string using HtmlDecode() method in HttpUtility object and also use Html helper Raw to return HtmlString. 

If there any a validation error you can show using ValidationMessageFor, it will display a message along with the image.

MVC Validation example:

validation message contains images

Post your comments / questions